package com.example.testsbjenkins.digui;


import cn.hutool.json.JSONUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: lt
 * @date: 2022/6/24 14:09
 * @Description: todo
 */
public class Test {

    public static void main(String[] args) {



        //模拟从数据库查询出来
        List<Menu> menus = Arrays.asList(
                new Menu(1,"根节点",0),
                new Menu(2,"子节点1",1),
                new Menu(3,"子节点1.1",2),
                new Menu(4,"子节点1.2",2),
                new Menu(5,"根节点1.3",2),
                new Menu(6,"根节点2",1),
                new Menu(7,"根节点2.1",6),
                new Menu(8,"根节点2.2",6),
                new Menu(9,"根节点2.2.1",7),
                new Menu(10,"根节点2.2.2",7),
                new Menu(11,"根节点3",1),
                new Menu(12,"根节点3.1",11)
        );

        //获取父节点
        List<Menu> menuList = menus.stream().filter(m -> Objects.equals(0,m.getParentId())).map(m->{
            m.setChildList(getChildrens(m,menus));
            return m;
        }).collect(Collectors.toList());

        System.out.println("-------转json输出结果-------");
        System.out.println(JSONUtil.toJsonStr(menuList));

    }

    private static List<Menu> getChildrens(Menu m, List<Menu> menus) {

        List<Menu> childrens = menus.stream().filter(c->Objects.equals(m.getId(),c.getParentId())).map(
                c->{
                    c.setChildList(getChildrens(c,menus));
                    return c;
                }
        ).collect(Collectors.toList());

        return childrens;
    }
}
